﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Collections;
using System.Configuration;
using System.Web.Mvc;
using System.Xml.Linq;
using XZL.Web.Biz;
using XZL.Web.Entity;
using XZL.Web.Da;
using wxDemoweb.wxModel;
using XZL.Web.MVC.WXModel;

namespace XZL.Web.MVC.Controllers
{
    public class CourseController : Controller
    {
        string address = ConfigurationManager.AppSettings["ServerAddress"];
        string appid = ConfigurationManager.AppSettings["appid"];
        string appsecret = ConfigurationManager.AppSettings["appsecret"];
        string redirecturi = ConfigurationManager.AppSettings["redirecturi"];
        string appkey = ConfigurationManager.AppSettings["appkey"];
        string mchid = ConfigurationManager.AppSettings["mchid"];

        protected Hashtable Parameters = new Hashtable();  //支付请求参数集合

        /// <summary>
        /// 获取session数据
        /// </summary>
        /// <returns></returns>
        private UserInfo GetMyInfo()
        {
            UserInfo user = new UserInfo();

            if (HttpContext.Session["MyInfo"] != null)
            {
                user = HttpContext.Session["MyInfo"] as UserInfo;
            }
            else
            {
                string url = Request.Url.AbsoluteUri.ToString();

                string inviteID = "1";
                if (HttpContext.Session["InviteID"] != null)
                {
                    inviteID = HttpContext.Session["InviteID"].ToString();
                }
                string link1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirecturi;
                string link2 = "&response_type=code&scope=snsapi_userinfo&state=" + url;
                Response.Redirect(link1 + inviteID + link2);
            }
            return user;
        }

        /// <summary>
        /// 课程列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            UserInfo user = GetMyInfo();
            ViewBag.InviteID = user.UserNum;

            string id = Request.QueryString["Type"];

            int tmp = 0;
            int isCharge = 0;
            int type = 0;
            if (id != null)
            {
                if (int.TryParse(id, out tmp))
                {
                    tmp = Convert.ToInt32(id);
                }
            }

            ViewBag.Num = tmp;
            int? count = 0;

            //最热
            if (tmp == 5)
            {
                List<Course> lsHot = CourseBiz.GetHotCourseList();
                ViewBag.CourseList = lsHot;
                return View();
            }
            //最新
            if (tmp == 6)
            {
                List<Course> lsNew = CourseBiz.GetNewCourseList();
                ViewBag.CourseList = lsNew;
                return View();
            }

            //收费课
            if (tmp == 8)
            {
                isCharge = 1;
            }
            //免费课
            else if (tmp == 7)
            {
                isCharge = 2;
            }
            if (tmp <= 4)
            {
                type = tmp;
            }

            List<Course> ls = CourseBiz.GetCourseList("", type, isCharge, 0, 1, 100, ref count);
            ViewBag.CourseList = ls;
            return View();
        }

        /// <summary>
        /// 课程信息 + 视频列表
        /// </summary>
        /// <returns></returns>
        public ActionResult CourseInfo()
        {
            string inviteID = "";
            string id1 = Request.QueryString["InviteID"];
            string id2 = Request.QueryString["amp;InviteID"];
            if (id1 != null)
            {
                inviteID = id1;
            }
            else if (id2 != null)
            {
                inviteID = id2;
            }

            if (inviteID == null || inviteID == "")
            {
                if (HttpContext.Session["InviteID"] != null)
                {
                    inviteID = HttpContext.Session["InviteID"].ToString();
                }
                else
                {
                    inviteID = "1";
                }
            }
            HttpContext.Session["InviteID"] = inviteID;

            UserInfo user = GetMyInfo();
            ViewBag.UserID = user.UserID;
            ViewBag.InviteID = user.UserNum;
            string id = Request.QueryString["CourseID"];
            int? count = 0;
            int courseID = 0;
            try
            {
                courseID = Convert.ToInt32(id);
            }
            catch
            {
                courseID = 0;
            }
            Course cor = CourseBiz.GetCourseInfo(Convert.ToInt32(courseID));
            if (cor != null)
            {
                ViewBag.CourseInfo = cor;

                //判断收藏
                int res = CourseBiz.IsMyCourse(user.UserID, cor.CourseID, 3);
                ViewBag.IsCourse = res.ToString();

                //判断是否购买   小于0：未购买
                int buy1 = CourseBiz.IsMyCourse(user.UserID, cor.CourseID, 1);
                int buy2 = CourseBiz.IsMyCourse(user.UserID, cor.CourseID, 2);
                ViewBag.IsBuy = buy1 + buy2;
                if (user.WeiXinID == "oEJrzt6M8xGDWXGJB0J8Gd4KQev4") //测试员
                {
                    ViewBag.IsBuy = 0;
                }

                //推荐列表
                List<Course> lsInvite = CourseBiz.GetInviteList(cor.RelatedCourse);
                ViewBag.InviteList = lsInvite;

                //评价
                List<Proc_Comment_SelectListResult> lsComment = CourseBiz.GetCommentList(cor.CourseTeamID);
                ViewBag.CommetList = lsComment;
                ViewBag.CommentCount = "(" + lsComment.Count + ")";

                //记录点击次数
                CourseBiz.CourseClick(courseID);

                //视频列表
                List<Proc_CourseItem_SelectListByCourseIDResult> ls = CourseBiz.GetCourseItemList(courseID, 1, 6, ref count);
                if (ls != null)
                {
                    ViewBag.VideoList = ls;
                }

                //分享参数
                wxshareHandler wxsh = new wxshareHandler();
                string token = wxsh.GetToken();
                string ticket = wxsh.GetTicket(token);
                int timestamp = wxsh.ConvertDateTimeInt(DateTime.Now);
                string nonceStr = wxsh.GenerateCheckCode(16);
                string url = address + "Course/CourseInfo?CourseID=" + courseID + "&InviteID=" + user.UserNum;
                string sign = wxsh.GetSignature(ticket, nonceStr, timestamp.ToString(), url);

                ViewBag.AppID = appid;
                ViewBag.Token = token;
                ViewBag.Ticket = ticket;
                ViewBag.Timestamp = timestamp.ToString();
                ViewBag.NonceStr = nonceStr;
                ViewBag.Sign = sign;
                ViewBag.Url = url;
                ViewBag.Address = address;
            }

            return View();
        }

        /// <summary>
        /// 提交评价
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="courseID"></param>
        /// <param name="courseText"></param>
        /// <returns></returns>
        public JsonResult AddComment(string userID, int courseID, string content)
        {
            bool b = CourseBiz.AddComment(userID, courseID, content);
            return Json(b);
        }

        /// <summary>
        /// 点赞
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="commentID"></param>
        /// <returns></returns>
        public JsonResult Parise(string userID, int commentID)
        {
            int i = CourseBiz.CommentParise(userID, commentID);
            return Json(i);
        }


        /// <summary>
        /// 视频播放页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CoursePlay(string id)
        {
            UserInfo user = GetMyInfo();
            ViewBag.UserID = user.UserID;

            int? count = 0;
            int itemID = Convert.ToInt32(id);
            Proc_CourseItem_SelectInfoByItemIDResult item = CourseBiz.GetCourseItemInfo(itemID);

            //未开播或已过期
            if (item.StartTime > DateTime.Now || item.StartTime.Value.AddHours(item.ValidTime) < DateTime.Now)
            {
                return RedirectToAction("NoPlay", "Course");
            }

            Course cor = CourseBiz.GetCourseInfo(Convert.ToInt32(item.CourseID));
            if (cor != null)
            {
                //判断是否购买   小于0：未购买
                int buy1 = CourseBiz.IsMyCourse(user.UserID, item.CourseID, 1);
                int buy2 = CourseBiz.IsMyCourse(user.UserID, item.CourseID, 2);
                int isBuy = buy1 + buy2;
                if (user.WeiXinID == "oEJrzt6M8xGDWXGJB0J8Gd4KQev4") //测试员
                {
                    isBuy = 0;
                }
                if (isBuy < 0)
                {
                    return RedirectToAction("NoPlay", "Course");
                }

                ViewBag.CourseInfo = cor;

                //评价
                List<Proc_Comment_SelectListResult> lsComment = CourseBiz.GetCommentList(cor.CourseTeamID);
                ViewBag.CommetList = lsComment;
                ViewBag.CommentCount = "(" + lsComment.Count + ")";
            }

            ViewBag.VideoList = CourseBiz.GetCourseItemList(item.CourseID, 1, 100, ref count);
            ViewBag.Video = item;
            return View();
        }

        /// <summary>
        /// 不允许播放
        /// </summary>
        /// <returns></returns>
        public ActionResult NoPlay()
        {
            return View();
        }

        /// <summary>
        /// 收藏/取消收藏
        /// </summary>
        /// <returns></returns>
        public JsonResult CollectCourse(string userID, string courseID)
        {
            int cID = Convert.ToInt32(courseID);
            int res = CourseBiz.CollectCourse(userID, cID);
            return Json(res);
        }

        /// <summary>
        /// 购买课程[微信支付]
        /// </summary>
        /// <returns></returns>
        public ActionResult BuyCourse()
        {
            UserInfo user = GetMyInfo();
            ViewBag.InviteID = user.UserNum;
            string id = Request.QueryString["ID"];
            string openid = "";
            int courseID = Convert.ToInt32(id);
            Course cor = CourseBiz.GetCourseInfo(Convert.ToInt32(courseID));
            if (cor != null)
            {
                ViewBag.CourseInfo = cor;
                //判断是否购买   小于0：未购买
                int buy1 = CourseBiz.IsMyCourse(user.UserID, cor.CourseID, 1);
                int buy2 = CourseBiz.IsMyCourse(user.UserID, cor.CourseID, 2);
                ViewBag.IsBuy = buy1 + buy2;
            }

            if (user.WeiXinID != null && user.WeiXinID != "")
            {
                openid = user.WeiXinID;
            }
            else
            {
                Response.Redirect("~/home/index", false);
            }

            string sIp = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : Request.ServerVariables["REMOTE_ADDR"];

            wxHandleModel.wxPayconfig wxpayconfig = null;  //微信支付数据包
            wxpayHandler wxhand = new wxpayHandler();
            //微信JS-SDK 位置信息
            //wxHandleModel.wxJSconfig wxconfig = null;   //JS-SDK数据包
            //wxconfig = new wxHandleModel.wxJSconfig();
            //wxconfig = wxhand.GetTicket(Request.Url.ToString());
            //设置package订单参数
            SetParameter("appid", appid);         //公众账号ID
            SetParameter("body", "网非网络课堂"); //商品描述
            SetParameter("mch_id", mchid);        //商户号
            SetParameter("nonce_str", wxhand.GenerateCheckCode(16).ToLower());     //随机字符串
            SetParameter("notify_url", "!!!!!!!!!!!!!!!!!!!!!!!!!");//接收财付通通知的URL
            SetParameter("openid", openid);                     //openid
            SetParameter("out_trade_no", wxhand.ConvertDateTimeInt(DateTime.Now) + user.UserNum.ToString() + GetRandomNum(5));      //商家订单号
            string ordercode = Parameters["out_trade_no"].ToString();
            SetParameter("spbill_create_ip", sIp);   //用户的公网ip，不是商户服务器IP
            SetParameter("total_fee", (cor.Price * 100).ToString()); //商品金额,以分为单位(money * 100).ToString()
            string price = Parameters["total_fee"].ToString();
            SetParameter("trade_type", "JSAPI");                        //交易类型
                                                                        //签名，需要除sin以外所有的参数都得参与签名
            string sign = wxhand.getSin(Parameters, appkey);
            SetParameter("sign", sign);
            string pkxml = wxhand.getDataXML(Parameters);

            //发送给微信支付统一下单接口
            string urlFormat = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            var result = wxhand.GetPage(urlFormat, pkxml);
            //接收微信返回的xml数据
            var res = XDocument.Parse(result);
            try
            {
                if (res.Element("xml").Element("return_code").Value == "SUCCESS")
                {
                    //下单成功返回
                    string repayId = res.Element("xml").Element("prepay_id").Value;
                    wxpayconfig = new wxHandleModel.wxPayconfig();
                    wxpayconfig = wxhand.GetwxPay(repayId);
                    ViewBag.Info = "统一下单成功！";
                }
                else
                {
                    //下单失败返回
                    wxpayconfig = new wxHandleModel.wxPayconfig();
                    if (res.Element("xml").Element("return_msg").Value.Contains("openid"))
                    {
                        //如果错误信息为无效的openid,跳转到授权页面重新授权。
                        ViewBag.Info = "无效的openid";
                    }
                    else
                    {
                        //下单错误信息。
                        ViewBag.Info = "return_code:" + res.Element("xml").Element("return_code").Value + ",return_msg:" + res.Element("xml").Element("return_msg").Value;
                    }
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }

            ViewBag.Sign = sign;
            ViewBag.Pkxml = pkxml;
            ViewBag.Ordercode = ordercode;
            ViewBag.Price = price;
            ViewBag.Wxpayconfig = wxpayconfig;
            ViewBag.OpenID = openid;
            ViewBag.InviteID = user.UserNum;
            ViewBag.AppID = appid;
            return View();
        }

        /// <summary>
        /// 赠送课程
        /// </summary>
        /// <returns></returns>
        public ActionResult GiveCourse()
        {
            string inviteID = "";
            string id1 = Request.QueryString["InviteID"];
            string id2 = Request.QueryString["amp;InviteID"];
            if (id1 != null)
            {
                inviteID = id1;
            }
            else if (id2 != null)
            {
                inviteID = id2;
            }
            if (inviteID == null || inviteID == "")
            {
                if (HttpContext.Session["InviteID"] != null)
                {
                    inviteID = HttpContext.Session["InviteID"].ToString();
                }
                else
                {
                    inviteID = "1";
                }
            }
            HttpContext.Session["InviteID"] = inviteID;

            UserInfo user = GetMyInfo();
            string cID = Request.QueryString["CourseID"];

            string orderID = "";
            string od1 = Request.QueryString["OrderID"];
            string od2 = Request.QueryString["amp;OrderID"];
            if (id1 != null)
            {
                orderID = od1;
            }
            else if (id2 != null)
            {
                orderID = od2;
            }

            int courseID = Convert.ToInt32(cID);
            Course cor = CourseBiz.GetCourseInfo(Convert.ToInt32(courseID));
            ViewBag.CourseInfo = cor;

            int res = CourseBiz.GetCourse(user.UserID, courseID, orderID);
            ViewBag.Title = cor.CourseName;
            switch (res)
            {
                case 1:
                    {
                        ViewBag.Info = "课程已购买，请将此页面分享给您的好友！";
                        break;
                    }
                case -1:
                    {
                        ViewBag.Info = "您已拥有该课程，无法领取！";
                        break;
                    }
                case -2:
                    {
                        ViewBag.Info = "课程已领完！";
                        break;
                    }
                case 0:
                    {
                        ViewBag.Info = "恭喜您 已领取课程！";
                        break;
                    }
            }

            //分享参数
            wxshareHandler wxsh = new wxshareHandler();
            string token = wxsh.GetToken();
            string ticket = wxsh.GetTicket(token);
            int timestamp = wxsh.ConvertDateTimeInt(DateTime.Now);
            string nonceStr = wxsh.GenerateCheckCode(16);
            string url = address + "Course/GiveCourse?CourseID=" + courseID + "&OrderID=" + orderID + "&InviteID=" + user.UserNum;
            string sign = wxsh.GetSignature(ticket, nonceStr, timestamp.ToString(), url);

            ViewBag.AppID = appid;
            ViewBag.Token = token;
            ViewBag.Ticket = ticket;
            ViewBag.Timestamp = timestamp.ToString();
            ViewBag.NonceStr = nonceStr;
            ViewBag.Sign = sign;
            ViewBag.Url = url;
            ViewBag.Address = address;

            return View();
        }

        /// <summary>
        /// 购买记录&账单
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="courseID"></param>
        /// <returns></returns>
        public JsonResult PayCourse(string courseID, string orderID, double price, int type)
        {
            UserInfo user = GetMyInfo();
            string userID = user.UserID;
            double cPirce = 0;
            int res = 0;
            int cID = Convert.ToInt32(courseID);
            try
            {
                cPirce = Convert.ToDouble(price);
            }
            catch
            {

            }

            string payUser = "";
            string memo = "";
            int count = 1;
            if (type == 1)
            {
                payUser = userID;
                count = 0;
                memo = "购买网非课程";
            }
            else if (type == 2)
            {
                memo = "赠送网非课程";
            }

            int res1 = CourseBiz.AddUserCourse(cID, type, payUser, userID, orderID, count, memo);
            bool res2 = CourseBiz.AddAccountLog(userID, cPirce, 1, 1, orderID, memo);
            if (res1 != 0 || res2 != true)
            {
                res = -1;
            }

            return Json(res);
        }

        /// <summary>
        /// 设置发送数据包参数值
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="parameterValue"></param>
        public void SetParameter(string parameter, string parameterValue)
        {

            if (parameter != null && parameter != "")
            {
                if (Parameters.Contains(parameter))
                {
                    Parameters.Remove(parameter);
                }

                Parameters.Add(parameter, parameterValue);
            }

        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public string GetRandomNum(int length)
        {
            string str = "";
            Random ran = new Random();
            for (int i = 0; i < length; i++)
            {
                str += ran.Next(0, 9);
            }
            return str;
        }

    }
}